const {slugify} = require('transliteration');
const Base = require('./base.js');

const fs = require('fs');
const path = require('path');
const assert = require('assert');
const lodash = require('lodash');


module.exports = class extends Base {

    async _initialize() {
        await super._initialize();
    }

    async indexAction() {

        let Model = this.mongoose('Module');

        let modules = [{
            key: 'admin',
            title: 'admin'
        }];
        for (let module of await Model.getModules()) {
            modules.push({
                key: module['name'],
                title: module['name']
            })
        }

        this.assign({
            modules: modules,
        });

        await this.display('admin/menu/index');
    }

    async tableAction() {
        const p = this.query('page') || 1;

        const id = this.post('id');
        const module = this.post('module');
        const keywords = this.post('keywords');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {title: {$regex: keywords, $options: "$i"}},
                    {tip: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (module !== "") {
            queryParams = Object.assign(queryParams, {module: module});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.fail(4001, '没找到符合条件的记录');
                return;
            }
        }
        // think.logger.info(`search queryParams:${JSON.stringify(queryParams)}`);

        const Model=this.mongoose('Menu');
        const pageSize = await this.mongoose('Config').C('LIST_ROWS');
        const pageEntity = await Model.findPage({
            page: p,
            pageSize: pageSize
        }, '', queryParams, {}, {module: 'asc', rank: 'asc'});

        this.assign({
            records: pageEntity.data,
            pager: super.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
        });
        await this.display('admin/menu/table');
    }

    async deleteAction() {
        const id = this.post('id');
        const ids = id.split(',');
        const Model = this.mongoose('Menu');

        for (const i of ids) {
            await Model.findByIdAndRemove(i).exec();
        }
        this.success('/admin/menu/index', '模块删除成功');
    }

    // walk(dir) {
    //
    //     dir = path.resolve(this.app, dir);
    //
    //     const exist = fs.existsSync(dir);
    //     if (!exist) {
    //         return;
    //     }
    //
    //     const files = fs.readdirSync(dir);
    //     let list = [];
    //
    //     for (let file of files) {
    //         if (fs.statSync(path.resolve(dir, file)).isDirectory()) {
    //             list = list.concat(this.walk(path.resolve(dir, file)));
    //         } else {
    //             list.push(path.resolve(dir, file));
    //         }
    //     }
    //
    //     return list;
    // }

    async resetAction() {
        //遍历所有模块，更新不一致的信息，必须有info/menu.js文件
        const dir = path.join(__dirname, `/../..`);
        const exist = fs.existsSync(dir);
        if (!exist) {
            return;
        }

        //处理系统的菜单
        let list = ['common','admin']; //保存有模块配置信息的模块名称列表
        const Menu = this.mongoose('Menu');
        //需要重新授权菜单访问权限
        await this.mongoose('RoleMenu').remove().exec();

        //删除不在列表中的模块菜单
        await Menu.remove({module: {$nin: list}}).exec();

        for (let module of list) {
            if (fs.statSync(path.resolve(dir, module)).isDirectory()) {
                //判断是否存在模块配置文件:module/info/menu.js
                if (fs.existsSync(path.resolve(dir, module, 'info', 'menu.js'))) {
                    let script_path = path.join(__dirname, `/../../${module}/info/menu.js`);
                    if (fs.existsSync(script_path)) {
                        // console.log(`install menu ${script_path}`);
                        const menu = require(script_path);
                        if (typeof menu === 'function') {
                            await menu();//安装菜单
                        }
                    }

                }
            }
        }


        //重新安装已经安装的应用模块的菜单
        const files = fs.readdirSync(dir);
        for (let file of files) {
            if (fs.statSync(path.resolve(dir, file)).isDirectory()) {
                //判断是否存在模块配置文件:module/info/menu.js
                if (fs.existsSync(path.resolve(dir, file, 'info', 'menu.js'))) {
                    const module = await this.mongoose('Module').findOne({name: file, isSetup: true}).exec();
                    //只加载已经安装的模块的菜单
                    if (module) {
                        let script_path = path.join(__dirname, `/../../${module['name']}/info/menu.js`);
                        if (fs.existsSync(script_path)) {
                            console.log(`install menu ${script_path}`);
                            const menu = require(script_path);
                            if (typeof menu === 'function') {
                                await menu();//安装菜单
                            }
                        }
                    }
                }
            }
        }

        this.redirect('/admin/menu/index');
    }

    async add() {
        if (this.isPost()) {
            const menu = this.post;
            this.model('admin/Menu').saveOrUpdate(menu);
            this.success('/admin/menu/index', '保存成功');
        } else {
            //Edit
            const Model = this.model('admin/Menu');
            if (this.query.id) {
                const menu = await Model.findOne({_id: this.query.id}).exec();
                await this.render('admin/menu/add', {menu: menu});
            } else {
                this.error('admin/menu/index', '不能手动添加模块。')
            }
        }
    }
}